import Vue from 'vue'
import Router from 'vue-router'

import Login from '@/components/Login'
import NotFound from '@/components/404'
import Index from '@/components/Index'
import Member from '@/components/user/Member'
import Supplier from '@/components/user/Supplier'
import Admin from '@/components/user/Admin'
import GoodsList from '@/components/goods/GoodsList'
import OrderList from '@/components/order/OrderList'
import Refound from '@/components/order/Refound'
import Api from '@/components/resource/Api'
import Role from '@/components/resource/Role'
import China from '@/components/DataList'

Vue.use(Router)

const router =  new Router({
  mode: 'history',
  routes: [
    {
      path: '/',
      name: 'Login',
      component: Login,
      hidden: true
    },
    {
      path: '/index',
      name: '',
      component: Index,
      meta: {
        requiresAuth: true,  // 添加该字段，表示进入这个路由是需要登录的
      },
      hidden: true,
    },
    {
        path: '/index',
        component: Index,
        name: '',
        iconCls: 'fa fa-home',
        leaf: true,//只有一个节点
        children: [
            { path: '/china', component: China, name: 'HOME' },
        ]
    },
    {
      path: '/index',
      name: '用户管理',
      component: Index,
      iconCls: 'fa fa-user-circle-o',      // font awesome 图标样式class
        children: [
            { path: '/member', component: Member, name: '会员管理' },
            { path: '/supplier', component: Supplier, name: '商家管理' },
            { path: '/admin', component: Admin, name: '管理员管理' },
        ]
    },
    {
      path: '/index',
      name: '团购管理',
      component: Index,
      iconCls: 'fa fa-snowflake-o',      // font awesome 图标样式class
        children: [
            { path: '/goods', component: GoodsList, name: '团购项目管理' },
        ]
    },
    {
      path: '/index',
      name: '订单管理',
      component: Index,
      iconCls: 'fa fa-file-text-o',    // font awesome 图标样式class
        children: [
            { path: '/orderlist', component: OrderList, name: '订单详情' },
            { path: '/refound', component: Refound, name: '退单审核' },
        ]
    },
    {
      path: '/index',
      name: '资源配置',
      component: Index,
      iconCls: 'fa fa-spinner',      // font awesome 图标样式class
        children: [
            { path: '/api', component: Api, name: 'API管理' },
            { path: '/role', component: Role, name: '角色管理' },
        ]
    },
    {
      path: '/404',
      name: '',
      component: NotFound,
      hidden: true
    }
  ]
})

// 注册全局钩子用来拦截导航
router.beforeEach((to, from, next) => {
  let token = window.localStorage.getItem('token')
  if (to.meta.requiresAuth) {
    if (token) {
      console.log(token)
      next()
    } else {
      store.dispatch('logOut')
      next({
        path: '/',
        query: { redirect: to.fullPath }
      })
    }
  } else {
    next()
  }
})

export default router
